package com.ylbh.common.utils;

import io.swagger.annotations.Api;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpStatus;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: czx
 * @date: 2019/10/14 11:07
 */
@Api("麦讯通推广群发")
public class ExtensionSms {

    public static String batchSendSms(String iphone, String contents){
        //请求第三方平台连接
        String url = "http://www.mxtong.net.cn/GateWay/Services.asmx/DirectSend?";
        HttpClient httpClient = new HttpClient();
        httpClient.getParams().setBooleanParameter("http.protocol.expect-continue", false);
        PostMethod getMethod = new PostMethod(url);
        try {//设置短信内容，短信内容格式 签名+内容+提示退订
            String content= java.net.URLEncoder.encode("【亿联百汇】"+contents+"回T退订", "UTF-8");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            NameValuePair[] data = {
                    new NameValuePair("UserID", "911095"),//用户ID
                    new NameValuePair("Account", "admin"),//字用户名
                    new NameValuePair("Password", "2JLANL"),//密码
                    new NameValuePair("Phones", iphone),//要发送的电话号码 "18665962906;13560452807;18123313611;"
                    new NameValuePair("SendType", "1"),//发送类型默认为1
                    new NameValuePair("SendTime", ""),//设置定时发送  ""为立即发送
                    new NameValuePair("PostFixNumber", ""),//任务扩展号(1到9,或者为空)
                    new NameValuePair("Content", content) };//短信内容
            getMethod.setRequestBody(data);
            getMethod.addRequestHeader("Connection", "close");
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("Method failed: "+ getMethod.getStatusLine());
            }
            byte[] responseBody = getMethod.getResponseBody();
            String str = new String(responseBody, "utf-8");
            System.out.println("str:"+str);
            if (str.contains("GBK")) {
                str = str.replaceAll("GBK", "utf-8");
            }
            int beginPoint = str.indexOf("<RetCode>");
            int endPoint = str.indexOf("</RetCode>");
            return str.substring(beginPoint + 9, endPoint);//返回Sucess  Faild
        } catch (Exception e) {
            return "Faild";
        } finally {
            getMethod.releaseConnection();
        }
    }

    public static void main(String[] args) {
        String sms = batchSendSms("13413325778", "测试一下推广短信的发送");
        System.out.println(sms);
    }
}
